//
//  560. 和为k的子数组.swift
//  LeetCodeTrain
//
//  Created by rjb on 2021/5/23.
//  Copyright © 2021 rjb. All rights reserved.
//

import Foundation
class Solution560 {
    // 采用双指针法
    // 或者滑动窗口的解法
    func subarraySum(_ nums: [Int], _ k: Int) -> Int {
        var left = 0
        var right = 0
        var sum = 0
        var result = 0
        while right < nums.count {
            if sum < k {
                sum += nums[right]
                right += 1
            } else if sum == k {
                sum -= nums[left]
                left += 1

                right += 1
                if right < nums.count {
                    sum += nums[right]
                }
                result += 1
            } else {
                sum -= nums[left]
                left += 1
            }
        }
        return result
    }
    static func test(){
//        let nums = [1,2,3]
        let nums = [1,1,1]
        let solution = Solution560()
        let result = solution.subarraySum(nums, 2)
        print(result)
    }
}
